package com.wakala.employment.fragment.other;

import static com.tamsiree.rxpay.wechat.pay.WechatPayTools.getCurrTime;
import static com.tamsiree.rxpay.wechat.pay.WechatPayTools.getMapFromXML;
import static com.tamsiree.rxpay.wechat.pay.WechatPayTools.getRandomStringByLength;
import static com.tamsiree.rxpay.wechat.pay.WechatPayTools.getSign;
import static com.tamsiree.rxpay.wechat.pay.WechatPayTools.parseString2Xml;
import static com.tamsiree.rxpay.wechat.pay.WechatPayTools.wechatPayApp;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hjq.toast.Toaster;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.tamsiree.rxkit.RxTool;
import com.tamsiree.rxkit.TLog;
import com.tamsiree.rxkit.interfaces.OnSuccessAndErrorListener;
import com.tamsiree.rxpay.wechat.pay.WechatModel;
import com.tamsiree.rxpay.wechat.pay.WechatPayModel;
import com.tamsiree.rxpay.wechat.pay.WechatPayTools;
import com.wakala.employment.R;
import com.wakala.employment.core.constants.Constants;
import com.wakala.employment.core.webview.BaseWebViewFragment;
import com.wakala.employment.databinding.FragmentMemberVipBinding;
import com.wakala.employment.databinding.FragmentUserCouponBinding;
import com.wakala.employment.http.manager.TokenManager;
import com.wakala.employment.utils.OrderUtil;
import com.wakala.employment.utils.Utils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.data.DateUtils;
import com.xuexiang.xutil.net.JsonUtil;
import com.xuexiang.xutil.system.DeviceUtils;

import org.xml.sax.SAXException;

import java.io.IOException;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.xml.parsers.ParserConfigurationException;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MemberVipFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class MemberVipFragment extends BaseWebViewFragment<FragmentMemberVipBinding> implements View.OnClickListener {
    private Handler mHandler = new Handler(Looper.getMainLooper());


    @NonNull
    @Override
    protected FragmentMemberVipBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentMemberVipBinding.inflate(inflater, container, attachToRoot);
    }

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.setTitle("我的会员");
        titleBar.setTitleColor(R.color.white);
        titleBar.setLeftTextColor(R.color.white);
        titleBar.setLeftImageDrawable(getResources().getDrawable(R.drawable.icon_arrow_white));
        titleBar.setBackgroundResource(R.color.colorBgKingYellow);//设置标题栏背景
        //StatusBarUtil.setLightMode(getActivity());
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.colorBgKingYellow));
        return titleBar;
    }

    @Override
    protected void initViews() {
        mAgentWeb = Utils.createAgentWeb(this, binding.container, "file:///android_asset/apphyvip/index.html");
        mAgentWeb.getJsInterfaceHolder().addJavaObject("Android", new AndroidInterface());
        mAgentWeb.getAgentWebSettings().getWebSettings().setAllowUniversalAccessFromFileURLs(true);
        mAgentWeb.getAgentWebSettings().getWebSettings().setAllowFileAccessFromFileURLs(true);
    }


    @Override
    public void onClick(View view) {

    }

    private void openMember1(String productId,String price){
        //XToastUtils.toast("选择的套餐ID="+productId);
        /*new XPopup.Builder(getContext()).asCustom(new CenterPopupView(requireContext()) {
            @Override
            protected int getImplLayoutId() {
                return R.layout.dialog_alter;
            }

            @Override
            protected void onCreate() {
                super.onCreate();
                findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });
                TextView title = findViewById(R.id.txt_dialog_content);
                title.setText("尊敬的用户，河狸帮给新用户赠送免费体验会员功能权益，您无需开通VIP会员套餐，就可免费使用所有会员功能，权益截至时间请关注系统通知消息");
            }
        }).show();*/
        try {
            int price_yuan = Integer.parseInt(price);
            int price_fen = price_yuan * 100;
            wechatPayUnifyOrder(String.valueOf(price_fen));
        }catch (Exception e){
            XToastUtils.error("支付金额异常，请检查");
        }

    }
    public void  wechatPayUnifyOrder(String money){
        String appid="wxe8a910123413ba65";//微信开发平台 河狸帮APP的 appid
        String mch_id="1657381524";//淼淼焱焱科技商户号
        String wx_private_key="dbc843cd027af59eaf8e807d969ae67f";
        String device_info=  DeviceUtils.getManufacturer()+";"+DeviceUtils.getDeviceModel()+";"+DeviceUtils.getAndroidID();
        String orderNo =   OrderUtil.generateOrderNumber();;
        WechatModel wechatModel = new WechatModel(orderNo,money,"会员开通","河狸帮VIP会员开通");
        String nonce_str = getRandomStringByLength(8);//随机码
        String body = wechatModel.getDetail();//商品描述
        String out_trade_no = wechatModel.getOut_trade_no();//商品订单号
        String product_id = wechatModel.getOut_trade_no();//商品编号
        String total_fee = wechatModel.getMoney();//总金额 分
        String time_start = getCurrTime();//交易起始时间(订单生成时间非必须)
        String trade_type = "APP";//App支付
        String notify_url = Constants.WX_PAY_NOTIFY_API_URI;//"http://" + "域名" + "/" + "项目名" + "回调地址.do";//回调函数
        SortedMap<String, String> params = new TreeMap<String, String>();
        params.put("appid", appid);
        params.put("mch_id", mch_id);
        params.put("device_info", device_info); //设备号
        params.put("nonce_str", nonce_str);
        params.put("body", body);//商品描述
        params.put("out_trade_no", out_trade_no);
        params.put("product_id", product_id);
        params.put("total_fee", total_fee);
        params.put("time_start", time_start);
        params.put("trade_type", trade_type);
        params.put("notify_url", notify_url);
        String sign = "";//签名(该签名本应使用微信商户平台的API证书中的密匙key,但此处使用的是微信公众号的密匙APP_SECRET)
        sign = getSign(params, wx_private_key);
        //参数xml化
        String xmlParams = parseString2Xml(params, sign);
        //判断返回码
        final String[] jsonStr = {""};

        OkGo.<String>post(com.tamsiree.rxkit.RxConstants.WX_TOTAL_ORDER)
                .upString(xmlParams)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        String s = response.body();
                        TLog.d("微信统一下单", s);
                        jsonStr[0] = s;

                        Map<String, String> mapXml = null;
                        try {
                            mapXml = getMapFromXML(s);
                        } catch (ParserConfigurationException | IOException | SAXException e) {
                            e.printStackTrace();
                        }
                        String time = getCurrTime();

                        SortedMap<String, String> params = new TreeMap<String, String>();
                        params.put("appid", appid);
                        params.put("noncestr", "5K8264ILTKCH16CQ2502SI8ZNMTM67VS");
                        params.put("package", "Sign=WechatPay");
                        params.put("partnerid", mch_id);
                        params.put("prepayid", mapXml.get("prepay_id"));
                        params.put("timestamp", time);
                        //
                        String sign = getSign(params, wx_private_key);

                        WechatPayModel wechatPayModel = new WechatPayModel(appid, mch_id, params.get("prepayid"), "Sign=WechatPay", params.get("noncestr"), params.get("timestamp"), sign);
                        String pay_param = JsonUtil.toJson(wechatPayModel);
                        //
                        //openNewPage(BlankFragment.class, "message",JsonUtil.toJson(pay_param));

                        wechatPayApp(getContext(), appid, mch_id, wx_private_key, params, new OnSuccessAndErrorListener(){

                            @Override
                            public void onSuccess(@Nullable String s) {
                                Toaster.showLong(s);
                            }

                            @Override
                            public void onError(@Nullable String s) {
                                Toaster.showLong(s);
                            }
                        });
                    }
                });
    }

    public  class AndroidInterface {

        @JavascriptInterface
        public void callAndroid(final String msg) {
            XToastUtils.toast("这是Js调用Android的方法，内容:" + msg);
        }
        @JavascriptInterface
        public void  toRecord(){
            openNewPage(UserIntegralRecordFragment.class);
        }
        @JavascriptInterface
        public void  openMember(String productId,String price){
            openMember1(productId,price);
            //XToastUtils.toast("未提供应用市场上线链接应用不能发起支付");
        }

        @JavascriptInterface
        public String getToken(){
            return TokenManager.getInstance().getToken();
        }

    }

}